/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.com.pps.common.util;

import java.util.Enumeration;
import java.util.Properties;
import org.springframework.util.ObjectUtils;

/**
 *
 * @author Dai
 */
public class PropertyPlaceholderConfigurer extends
        org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {

    private static final String ENCRYPTED = "encrypted.";
    // private MyFavoriteEncryptor encryptor = new MyFavoriteEncryptor();

    @Override
    protected void convertProperties(Properties props) {
        Enumeration propertyNames = props.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String) propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            String convertedValue = "";
            if (propertyName.startsWith(ENCRYPTED)) {
                // just store the property name without the encrypted prepended value 
                // so encrypted.jdbc.password becomes jdbc.password 
                propertyName = propertyName.substring(ENCRYPTED.length());
                convertedValue = decryptPropertyValue(propertyValue);
            } else {
                convertedValue = convertPropertyValue(propertyValue);
            }

            if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
                props.setProperty(propertyName, convertedValue);
            }
        }
    }

    protected String decryptPropertyValue(String base64EncryptedValue) {

        String decryptedValue = null;
        try {
            DesEncrypter desEncrypter = new DesEncrypter("PBEWithMD5AndDES");
            decryptedValue = desEncrypter.decrypt(base64EncryptedValue);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }

        return decryptedValue;
    }

    public PropertyPlaceholderConfigurer() {
        super();
    }

}
